<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class M_grading_system Extends MY_Model
{
	protected $_table = "grading_system";
	protected $_timestamp = false;
	
	public function __construct()
	{
		parent::__construct();
	}
	
	/**
	 * Check Value if lesser of equal to the highest score in grading system table
	 * @param FLOAT $value
	 * @return boolean
	 */
	public function check_numeric_grade($value)
	{
		if(floatval($value) <= $this->maximum_score()){
			RETURN TRUE;
		}	
		return FALSE;
	}

	/**
	 * Get Highest Maximum Grade / Score
	 * @return float
	 */
	public function maximum_score()
	{
		$sql = "SELECT MAX(range_end) AS maximum FROM $this->_table";
		$rs = $this->query($sql,false, true);
		if($rs){
			return $rs->maximum;
		}
		return 0;
	}

	/**
	 * Get Badge - for coloring the grade
	 * @param float $value
	 * @return string
	 */
	public function get_badge($value)
	{
		$rs = $this->numeric_to_letter($value, true , true);
		if($rs){
			if(empty($rs->badge)){
				$this->create_letter_badge($rs->letter, $rs->id);
				$rs = $this->numeric_to_letter($value, true , true);
			}

			return $rs->badge;
		}

		return "";
	}

	/**
	 * Convert Numeric to letter
	 * @param float $value
	 * @param string
	 */
	public function numeric_to_letter($value, $round = true, $return_obj = false)
	{
		$sql = "SELECT badge,letter, id
						FROM grading_system
						WHERE (? >= range_start AND ? <= range_end )
						LIMIT 1";
		if($round){
			$rs = $this->query($sql,[round($value), round($value)], true);
		}else{
			$rs = $this->query($sql,[intval($value), intval($value)], true);
		}
		// if($value == 0){
		// 	vd($rs);
		// }
		if($return_obj){
			return $rs;
		}

		if($rs){
			return $rs->letter;
		}

		return false;
	}

	/**
	 * Create Default Letter Badge
	 * @param string $letter
	 * @param int $id
	 */
	public function create_letter_badge($letter ='', $id)
	{
		switch (strtoupper($letter[0])) {
			case 'A':
				$badge = "info";
				break;
			case 'B':
				$badge = "success";
				break;
			case 'C':
				$badge = "warning";
				break;
			case 'D':
				$badge = "important";
				break;
			
			default:
				$badge = "";
				break;
		}

		unset($data);
		$data['badge'] = $badge;
		return $this->update($id, $data);
	}
}